package lexer;

import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Buffered adapter for using {@link GeneratedLexer} with the {@link Lexer}
 * interface.
 * 
 * @author ayc44
 */
public class Lexer implements Iterator<Token> {

  private ExpressionLexer lexer;
  private Token nextToken;

  public Lexer(Reader reader) {
    lexer = new ExpressionLexer(reader);
    bufferNext();
  }

  public Lexer(Reader reader, String unit) {
    lexer = new ExpressionLexer(reader, unit);
    bufferNext();
  }

  private void bufferNext() {
    try {
      nextToken = lexer.yylex();
    } catch (IOException e) {
      e.printStackTrace();
      throw new Error(e);
    }
  }

  @Override
  public Token next() {
    Token returnValue = nextToken;
    bufferNext();

    if (returnValue == null) {
      throw new NoSuchElementException();
    }
    return returnValue;
  }

  @Override
  public void remove() {
    throw new NoSuchElementException();
  }

  @Override
  public boolean hasNext() {
    return !lexer.hasReadEOF();
  }
}